package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author: 爱学Java 不想秃头的 KK
 * @date: 2023/7/26 8:07
 * @version: 1.0
 * @Created with IntelliJ IDEA.
 * @Description:
 */
@ControllerAdvice(annotations = {Repository.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 添加员工重复异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String [] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在!";
            log.info(msg);
            return R.error(msg);
        }
        return  R.error("未知错误!");
    }

    /**
     * 添加菜品或套餐无法直接删除异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.info(ex.getMessage());

        return  R.error(ex.getMessage());
    }
}
